﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Text;
using System.Text.RegularExpressions;

namespace YTCMS.Core.File
{
    #region WatermarkPms参数
    public enum WatermarkPms_Position
    {
        /// <summary>
        /// 左上
        /// </summary>
        Left_Top = 1,
        /// <summary>
        /// 中上
        /// </summary>
        Center_Top = 2,
        /// <summary>
        /// 右上
        /// </summary>
        Right_Top = 3,
        /// <summary>
        /// 左中
        /// </summary>
        Left_Center = 4,
        /// <summary>
        /// 居中
        /// </summary>
        Center_Center = 5,
        /// <summary>
        /// 右中
        /// </summary>
        Right_Center = 6,
        /// <summary>
        /// 左下
        /// </summary>
        Left_Bottom = 7,
        /// <summary>
        /// 中下
        /// </summary>
        Center_Bottom = 8,
        /// <summary>
        /// 右下
        /// </summary>
        Right_Bottom = 9,
    }

    public enum WatermarkPms_Type
    {
        /// <summary>
        /// 文字水印
        /// </summary>
        Txt = 0,

        /// <summary>
        /// 图片按位置摆放
        /// </summary>
        Img_Put = 1,
        /// <summary>
        /// 图片裁剪
        /// </summary>
        Img_Cut = 2,
    }
    public class WatermarkPms_Img
    {
        /// <summary>
        /// 水印图片路径
        /// </summary>
        public string Path { get; set; }
        /// <summary>
        /// 位置
        /// </summary>
        public WatermarkPms_Position Position { get; set; }
        /// <summary>
        /// 透明度(1-10,10为不透明)
        /// </summary>
        public int Transparency { get; set; }
    }
    public class WatermarkPms_Txt
    {
        /// <summary>
        /// 文本
        /// </summary>
        public string Text { get; set; }
        /// <summary>
        /// 字体大小
        /// </summary>
        public int FontSize { get; set; }
        /// <summary>
        /// 位置
        /// </summary>
        public WatermarkPms_Position Position { get; set; }
    }

    public class WatermarkPms
    {
        public WatermarkPms_Type type { get; set; }
        public WatermarkPms_Img img_pms { get; set; }
        public WatermarkPms_Txt txt_pms { get; set; }

        public static WatermarkPms default_val
        {
            get
            {
                return null;
            }
        }
    }

    #endregion

    public enum ThumbnailType
    {
        /// <summary>
        /// 头像
        /// </summary>
        Logo,
        /// <summary>
        /// 照片
        /// </summary>
        Photo
    }

    public class ThumbnailHelper
    {
        /// <summary>
        /// 得到图片格式
        /// </summary>
        /// <param name="name">文件名称</param>
        /// <returns></returns>
        public static ImageFormat GetFormat(string name)
        {
            string ext = name.Substring(name.LastIndexOf(".") + 1);
            switch (ext.ToLower())
            {
                case "jpg":
                case "jpeg":
                    return ImageFormat.Jpeg;
                case "bmp":
                    return ImageFormat.Bmp;
                case "png":
                    return ImageFormat.Png;
                case "gif":
                    return ImageFormat.Gif;
                default:
                    return ImageFormat.Jpeg;
            }
        }

        /// <summary>
        /// 按比例缩放图片
        /// </summary>
        /// <param name="fileName">源图片</param>
        /// <param name="newFileName">缩略图保存路径</param>
        /// <param name="width">缩略图宽度</param>
        public static void MakeThumbnailImage(string fileName, string newFileName, int width, WatermarkPms warter = null)
        {
            using (Bitmap bmp = new Bitmap(fileName))
            {
                double scale = (double)bmp.Width / width;
                double height = (double)bmp.Height / scale;
                //Image.ThumbMode mode = mode = Image.ThumbMode.Max;
                ContentAlignment contentAlignment = ContentAlignment.TopLeft;
                using (Bitmap image = Image.Thumbnail(bmp, new Size(width, (int)height), contentAlignment, ThumbnailType.Photo))
                {
                    MakeWarterPic(image, warter);
                    Image.SaveIamge(image, 100L, newFileName);
                }
            }
        }

        /// <summary>
        /// 按用户指定长宽缩放图片
        /// </summary>
        /// <param name="fileName">源图片</param>
        /// <param name="newFileName">缩略图保存路径</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        public static void MakeThumbnailImage(string fileName, string newFileName, int width, int height, WatermarkPms warter = null, ThumbnailType type = ThumbnailType.Photo)
        {
            using (Bitmap bmp = new Bitmap(fileName))
            {
                Image.ThumbMode mode = mode = Image.ThumbMode.Max;
                ContentAlignment contentAlignment = ContentAlignment.TopLeft;
                using (Bitmap image = Image.Thumbnail(bmp, new Size(width, height), contentAlignment, type))
                {
                    MakeWarterPic(image, warter);
                    Image.SaveIamge(image, 100L, newFileName);
                }
            }
        }
        public static void MakeWarterPic(string fileName, WatermarkPms warter)
        {
            Bitmap image = null; string newFileName_tmp = null;
            try
            {
                if (! System.IO.File.Exists(fileName))
                    return;
                if (warter == null)
                    return;
                if (warter.type == WatermarkPms_Type.Txt && (warter.txt_pms == null || string.IsNullOrWhiteSpace(warter.txt_pms.Text)))
                    return;
                if (warter.type == WatermarkPms_Type.Img_Cut && (warter.img_pms == null || string.IsNullOrWhiteSpace(warter.img_pms.Path)))
                    return;
                if (warter.type == WatermarkPms_Type.Img_Put && (warter.img_pms == null || string.IsNullOrWhiteSpace(warter.img_pms.Path)))
                    return;
                newFileName_tmp = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName) + "_warter_tmp" + Path.GetExtension(fileName));
                if (System.IO.File.GetAttributes(fileName).ToString().IndexOf("ReadOnly") != -1)
                {
                    System.IO.File.SetAttributes(fileName, FileAttributes.Normal);
                }
                System.IO.File.Copy(fileName, newFileName_tmp, true);
                image = new Bitmap(newFileName_tmp);
                MakeWarterPic(image, warter);
                string newFileName = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName) + "_33" + Path.GetExtension(fileName));
                Image.SaveIamge(image, 96L, fileName);
                //image.Save(fileName);
            }
            catch { }
            finally
            {
                if (image != null)
                    image.Dispose();
            }
            if (newFileName_tmp != null && System.IO.File.Exists(newFileName_tmp))
                System.IO.File.Delete(newFileName_tmp);
        }
        private static void MakeWarterPic(System.Drawing.Image image, WatermarkPms warter)
        {
            if (warter == null)
                return;
            if (warter.type == WatermarkPms_Type.Txt)
            {//【隆金宝LONGKIN.NET】
                if (warter.txt_pms != null && !string.IsNullOrWhiteSpace(warter.txt_pms.Text))
                    AddWatermarkText(image, warter.txt_pms.Text.Trim(), (int)warter.txt_pms.Position, warter.txt_pms.FontSize);
            }
            else if (warter.type == WatermarkPms_Type.Img_Put)
            {
                if (warter.img_pms != null && !string.IsNullOrWhiteSpace(warter.img_pms.Path))
                    AddWatermarkPic_Put(image, warter.img_pms.Path, (int)warter.img_pms.Position, warter.img_pms.Transparency);
            }
            else if (warter.type == WatermarkPms_Type.Img_Cut)
            {
                if (warter.img_pms != null && !string.IsNullOrWhiteSpace(warter.img_pms.Path))
                    AddWatermarkPic_Cut(image, warter.img_pms.Path, (int)warter.img_pms.Position, warter.img_pms.Transparency);
            }
        }

        /// <summary>
        /// 文字水印
        /// </summary>
        /// <param name="img">图片</param>
        /// <param name="watermarkText">水印文字</param>
        /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param> 
        /// <param name="fontsize">字体大小</param>
        private static void AddWatermarkText(System.Drawing.Image img, string watermarkText, int watermarkStatus, int fontsize)
        {
            Graphics g = Graphics.FromImage(img);
            try
            {
                string fontname = "arial";
                Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
                SizeF crSize;
                crSize = g.MeasureString(watermarkText, drawFont);
                float xpos = 0;
                float ypos = 0;
                switch (watermarkStatus)
                {
                    case 1:
                        xpos = (float)img.Width * (float).01;
                        ypos = (float)img.Height * (float).01;
                        break;
                    case 2:
                        xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                        ypos = (float)img.Height * (float).01;
                        break;
                    case 3:
                        xpos = ((float)img.Width * (float).99) - crSize.Width;
                        ypos = (float)img.Height * (float).01;
                        break;
                    case 4:
                        xpos = (float)img.Width * (float).01;
                        ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                        break;
                    case 5:
                        xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                        ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                        break;
                    case 6:
                        xpos = ((float)img.Width * (float).99) - crSize.Width;
                        ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                        break;
                    case 7:
                        xpos = (float)img.Width * (float).01;
                        ypos = ((float)img.Height * (float).99) - crSize.Height;
                        break;
                    case 8:
                        xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                        ypos = ((float)img.Height * (float).99) - crSize.Height;
                        break;
                    case 9:
                        xpos = ((float)img.Width * (float).99) - crSize.Width;
                        ypos = ((float)img.Height * (float).99) - crSize.Height;
                        break;
                }
                g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1);
                g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos);

                //ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                //ImageCodecInfo ici = null;
                //foreach (ImageCodecInfo codec in codecs)
                //{
                //    if (codec.MimeType.IndexOf("jpeg") > -1)
                //    {
                //        ici = codec;
                //    }
                //}
                //EncoderParameters encoderParams = new EncoderParameters();
                //long[] qualityParam = new long[1];
                //if (quality < 0 || quality > 100)
                //{
                //    quality = 80;
                //}
                //qualityParam[0] = quality;
                //EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
                //encoderParams.Param[0] = encoderParam;
                //if (ici != null)
                //{
                //    img.Save(filename, ici, encoderParams);
                //}
                //else
                //{
                //    img.Save(filename);
                //}
            }
            catch { }
            finally
            {
                g.Dispose();
                //bmp.Dispose();
                //img.Dispose();
            }
        }

        /// <summary>
        /// 图片水印(裁剪)
        /// </summary>
        /// <param name="img">图片</param>
        /// <param name="watermarkFilename">水印文件名</param>
        /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
        private static void AddWatermarkPic_Cut(System.Drawing.Image img, string watermarkFilename, int watermarkStatus, int watermarkTransparency)
        {
            if (!System.IO.File.Exists(watermarkFilename))
                return;

            var watermark = new Bitmap(watermarkFilename);
            var g = Graphics.FromImage(img);
            ImageAttributes imageAttributes = new ImageAttributes();
            try
            {
                //设置高质量插值法
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                //设置高质量,低速度呈现平滑程度
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //if (watermark.Height >= img.Height || watermark.Width >= img.Width)
                //{
                //    return;
                //} 

                ColorMap colorMap = new ColorMap();
                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                ColorMap[] remapTable = { colorMap };
                imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
                float transparency = 0.5F;
                if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
                {
                    transparency = (watermarkTransparency / 10.0F);
                }
                float[][] colorMatrixElements = {
                                                new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  0.0f,  0.0f,  transparency, 0.0f},
                                                new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                            };
                ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
                imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                //g.DrawImage(watermark, new Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imageAttributes); 
                int x_sc = (int)Math.Ceiling((double)img.Width / (double)watermark.Width);
                int y_sc = (int)Math.Ceiling((double)img.Height / (double)watermark.Height);
                for (var i = 0; i < x_sc; i++)
                {
                    for (var j = 0; j < y_sc; j++)
                    {
                        g.DrawImage(watermark, new Rectangle(i * watermark.Width, j * watermark.Height, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imageAttributes);
                    }
                }
            }
            catch
            {

            }
            finally
            {
                g.Dispose();
                //img.Dispose();
                watermark.Dispose();
                imageAttributes.Dispose();
            }
        }

        /// <summary>
        /// 图片水印(摆放)
        /// </summary>
        /// <param name="img">图片</param>
        /// <param name="watermarkFilename">水印文件名</param>
        /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
        private static void AddWatermarkPic_Put(System.Drawing.Image img, string watermarkFilename, int watermarkStatus, int watermarkTransparency)
        {
            if (!System.IO.File.Exists(watermarkFilename))
                return;
            Graphics g = Graphics.FromImage(img);
            System.Drawing.Image watermark_bk = new Bitmap(watermarkFilename);
            Bitmap watermark = null;
            ImageAttributes imageAttributes = new ImageAttributes();
            try
            {
                //设置高质量插值法
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                //设置高质量,低速度呈现平滑程度
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                watermark = KiRotate(watermark_bk, -45);
                if (watermark.Height >= img.Height || watermark.Width >= img.Width)
                {
                    return;
                }
                ColorMap colorMap = new ColorMap();
                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                ColorMap[] remapTable = { colorMap };
                imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
                float transparency = 0.5F;
                if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
                {
                    transparency = (watermarkTransparency / 10.0F);
                }
                float[][] colorMatrixElements = {
                                                new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  0.0f,  0.0f,  transparency, 0.0f},
                                                new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                            };
                ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
                imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                int xpos = 0;
                int ypos = 0;
                switch (watermarkStatus)
                {
                    case 1:
                        xpos = (int)(img.Width * (float).01);
                        ypos = (int)(img.Height * (float).01);
                        break;
                    case 2:
                        xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                        ypos = (int)(img.Height * (float).01);
                        break;
                    case 3:
                        xpos = (int)((img.Width * (float).99) - (watermark.Width));
                        ypos = (int)(img.Height * (float).01);
                        break;
                    case 4:
                        xpos = (int)(img.Width * (float).01);
                        ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                        break;
                    case 5:
                        xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                        ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                        break;
                    case 6:
                        xpos = (int)((img.Width * (float).99) - (watermark.Width));
                        ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                        break;
                    case 7:
                        xpos = (int)(img.Width * (float).01);
                        ypos = (int)((img.Height * (float).99) - watermark.Height);
                        break;
                    case 8:
                        xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                        ypos = (int)((img.Height * (float).99) - watermark.Height);
                        break;
                    case 9:
                        xpos = (int)((img.Width * (float).99) - (watermark.Width));
                        ypos = (int)((img.Height * (float).99) - watermark.Height);
                        break;
                }
                g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);
                //g.DrawImage(watermark, new System.Drawing.Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, System.Drawing.GraphicsUnit.Pixel);

                //ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                //ImageCodecInfo ici = null;
                //foreach (ImageCodecInfo codec in codecs)
                //{
                //    if (codec.MimeType.IndexOf("jpeg") > -1)
                //    {
                //        ici = codec;
                //    }
                //}
                //EncoderParameters encoderParams = new EncoderParameters();
                //long[] qualityParam = new long[1];
                //if (quality < 0 || quality > 100)
                //{
                //    quality = 80;
                //}
                //qualityParam[0] = quality;
                //EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
                //encoderParams.Param[0] = encoderParam;
                //if (ici != null)
                //{
                //    img.Save(filename, ici, encoderParams);
                //}
                //else
                //{
                //    img.Save(filename);
                //}
            }
            catch { }
            finally
            {
                g.Dispose();
                //img.Dispose();
                watermark_bk.Dispose();
                if (watermark != null)
                    watermark.Dispose();
                imageAttributes.Dispose();
            }
        }

        /// <summary>
        /// 图片旋转
        /// </summary>
        /// <param name="bmp"></param>
        /// <param name="angle"></param>
        /// <returns></returns>
        private static Bitmap KiRotate(System.Drawing.Image bmp, float angle)
        {
            int w = bmp.Width + 2;
            int h = bmp.Height + 2;
            PixelFormat pf = PixelFormat.Format32bppArgb;
            //if (bkColor == Color.Transparent)
            //{
            //    pf = PixelFormat.Format32bppArgb;
            //}
            //else
            //{
            //    pf = bmp.PixelFormat;
            //}
            Bitmap tmp = new Bitmap(w, h, pf);
            Graphics g = Graphics.FromImage(tmp);
            g.Clear(Color.Transparent);
            g.DrawImageUnscaled(bmp, 1, 1);
            g.Dispose();
            GraphicsPath path = new GraphicsPath();
            path.AddRectangle(new RectangleF(0f, 0f, w, h));
            Matrix mtrx = new Matrix();
            mtrx.Rotate(angle);
            RectangleF rct = path.GetBounds(mtrx);

            Bitmap dst = new Bitmap((int)rct.Width, (int)rct.Height, pf);
            g = Graphics.FromImage(dst);
            g.Clear(Color.Transparent);
            g.TranslateTransform(-rct.X, -rct.Y);
            g.RotateTransform(angle);
            g.InterpolationMode = InterpolationMode.HighQualityBilinear;
            g.DrawImageUnscaled(tmp, 0, 0);
            g.Dispose();
            tmp.Dispose();
            return dst;
        }

        private class Image
        {
            /// <summary>
            /// 缩略模式。
            /// </summary>
            public enum ThumbMode : byte
            {
                /// <summary>
                /// 完整模式
                /// </summary>
                Full = 1,
                /// <summary>
                /// 最大尺寸
                /// </summary>
                Max
            }

            /// <summary>
            /// 缩略图。
            /// </summary>
            /// <param name="image">要缩略的图片</param>
            /// <param name="size">要缩放的尺寸</param>
            /// <param name="mode">缩略模式</param>
            /// <param name="contentAlignment">对齐方式</param>
            /// <returns>返回已经缩放的图片。</returns>
            public static Bitmap Thumbnail(Bitmap image, Size size, ContentAlignment contentAlignment, ThumbnailType type)
            {

                if (image.Width <= size.Width && image.Height <= size.Height)
                {
                    if (type == ThumbnailType.Photo)
                        return image;
                }

                if (!size.IsEmpty && !image.Size.IsEmpty && !size.Equals(image.Size))
                {
                    //先取一个宽比例。
                    double scale = (double)image.Width / (double)size.Width;

                    if (image.Height > image.Width)
                        scale = (double)image.Height / (double)size.Height;
                    //缩略模式
                    //switch (mode)
                    //{
                    //    case ThumbMode.Full:
                    //        if (image.Height > image.Width)
                    //            scale = (double)image.Height / (double)size.Height;
                    //        break;
                    //    case ThumbMode.Max:
                    //        if (image.Height / scale < size.Height)
                    //            scale = (double)image.Height / (double)size.Height;
                    //        break;
                    //}

                    Size newSzie = new Size((int)(image.Width / scale), (int)(image.Height / scale));
                    Bitmap result = new Bitmap(newSzie.Width, newSzie.Height);

                    if (type == ThumbnailType.Logo)
                    {
                        newSzie = new Size(size.Width, size.Height);
                        result = new Bitmap(newSzie.Width, newSzie.Height);
                    }

                    using (Graphics g = Graphics.FromImage(result))
                    {
                        //背景颜色
                        g.FillRectangle(Brushes.Transparent, new Rectangle(new Point(0, 0), size));
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.SmoothingMode = SmoothingMode.HighQuality;
                        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        g.CompositingMode = CompositingMode.SourceOver;
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
                        //对齐方式
                        Rectangle destRect;
                        switch (contentAlignment)
                        {
                            case ContentAlignment.TopCenter:
                                destRect = new Rectangle(new Point(-((newSzie.Width - size.Width) / 2), 0), newSzie);
                                break;
                            case ContentAlignment.TopRight:
                                destRect = new Rectangle(new Point(-(newSzie.Width - size.Width), 0), newSzie);
                                break;
                            case ContentAlignment.MiddleLeft:
                                destRect = new Rectangle(new Point(0, -((newSzie.Height - size.Height) / 2)), newSzie);
                                break;
                            case ContentAlignment.MiddleCenter:
                                destRect = new Rectangle(new Point(-((newSzie.Width - size.Width) / 2), -((newSzie.Height - size.Height) / 2)), newSzie);
                                break;
                            case ContentAlignment.MiddleRight:
                                destRect = new Rectangle(new Point(-(newSzie.Width - size.Width), -((newSzie.Height - size.Height) / 2)), newSzie);
                                break;
                            case ContentAlignment.BottomLeft:
                                destRect = new Rectangle(new Point(0, -(newSzie.Height - size.Height)), newSzie);
                                break;
                            case ContentAlignment.BottomCenter:
                                destRect = new Rectangle(new Point(-((newSzie.Width - size.Width) / 2), -(newSzie.Height - size.Height)), newSzie);
                                break;
                            case ContentAlignment.BottomRight:
                                destRect = new Rectangle(new Point(-(newSzie.Width - size.Width), -(newSzie.Height - size.Height)), newSzie);
                                break;
                            default:
                                destRect = new Rectangle(new Point(0, 0), newSzie);
                                break;
                        }
                        g.DrawImage(image, destRect, new Rectangle(new Point(0, 0), image.Size), GraphicsUnit.Pixel);
                        image.Dispose();
                    }
                    return result;
                }
                else
                    return image;
            }

            /// <summary>
            /// 保存图片。
            /// </summary>
            /// <param name="image">要保存的图片</param>
            /// <param name="quality">品质（1L~100L之间，数值越大品质越好）</param>
            /// <param name="filename">保存路径</param>
            public static void SaveIamge(Bitmap image, long quality, string filename)
            {
                using (EncoderParameters encoderParams = new EncoderParameters(1))
                {
                    using (EncoderParameter parameter = (encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality)))
                    {
                        ImageCodecInfo encoder = null;
                        //取得扩展名
                        string ext = Path.GetExtension(filename);
                        if (string.IsNullOrEmpty(ext))
                            ext = ".jpg";
                        //根据扩展名得到解码、编码器
                        foreach (ImageCodecInfo codecInfo in ImageCodecInfo.GetImageEncoders())
                        {
                            if (Regex.IsMatch(codecInfo.FilenameExtension, string.Format(@"(;|^)\*\{0}(;|$)", ext), RegexOptions.IgnoreCase))
                            {
                                encoder = codecInfo;
                                break;
                            }
                        }
                        Directory.CreateDirectory(Path.GetDirectoryName(filename));
                        image.Save(filename, encoder, encoderParams);
                    }
                }
            }

            /// <summary>
            /// 保存图片。
            /// </summary>
            /// <param name="stream">要保存的流</param>
            /// <param name="quality">品质（1L~100L之间，数值越大品质越好）</param>
            /// <param name="filename">保存路径</param>
            public static void SaveIamge(Stream stream, long quality, string filename)
            {
                using (Bitmap bmpTemp = new Bitmap(stream))
                {
                    SaveIamge(bmpTemp, quality, filename);
                }
            }
        }
    }//end class
}
